import os.path
import socket  # 导入 socket 模块
from threading import Thread
import time
import json

ADDRESS = ('0.0.0.0', 10010)  # 绑定地址

g_socket_server = None  # 负责监听的socket

g_conn_pool = {}  # 连接池

# 读取学生信息
with open("./stu.txt","r") as f:
    stus = f.read().strip().split("\n")

def init():
    """
    初始化服务端
    """
    global g_socket_server
    g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    g_socket_server.bind(ADDRESS)
    g_socket_server.listen(100)  # 最大等待数（有很多人理解为最大连接数，其实是错误的）
    print("server start，wait for client connecting...")


def accept_client():
    """
    接收新连接
    """
    while True:
        client, info = g_socket_server.accept()  # 阻塞，等待客户端连接
        # 给每个客户端创建一个独立的线程进行管理
        thread = Thread(target=message_handle, args=(client, info))
        # 设置成守护线程
        thread.setDaemon(True)
        thread.start()


def message_handle(client, info):
    global stus
    """
    消息处理
    """
    client.sendall("connect server successfully!".encode(encoding='utf8'))
    while True:
        try:
            bytes = client.recv(1024)
            msg = bytes.decode(encoding='utf8').strip()
            info = info[0]
            if msg in stus:
                if os.path.exists("./ip/{}".format(info)):
                    # 说明重复提交
                    with open("./ip/{}".format(info),"r") as f:
                        stu_name = f.read()
                        if stu_name == msg:
                            # 说明是重复提交！
                            print("{}重复提交".format(stu_name))
                        else:
                            # 作弊了
                            with open("./cheat/{}".format(info), "a") as f2:
                                f2.write("{}_{}\n".format(stu_name,msg))
                else:
                    with open("./ip/{}".format(info), "w") as f:
                        f.write(msg)
                    with open("./stu/{}".format(msg), "w") as f:
                        f.write(info)
            client.sendall("提交成功！请勿重复提交，请勿帮助他人提交！".encode(encoding='utf8'))
            # print(msg, info)
        except Exception as e:
            client.close()
            break


if __name__ == '__main__':
    init()
    # 新开一个线程，用于接收新连接
    thread = Thread(target=accept_client)
    thread.setDaemon(True)
    thread.start()
    # 主线程逻辑
    while True:
        time.sleep(0.1)
